<?php

class MaterialsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *  全民喝好水
	 * @return Response
	 */
	public function index()
	{
		//

        $cart = Input::get('cart');
        if(!$cart){
            $cart = 0;
        }
        $pub = Pub::find(1);

        $PATH = $pub->path;
        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);
        $materials = Material::where('points','!=','0')->where('cart',$cart)->orderBy('created_at', 'DESC')->get();
        return View::make('materials.index', compact('materials','PATH','customer','cart'));
	}


    /**
     * 专属帖子
     */
    public function myindex(){
        $pub = Pub::find(1);

        $PATH = $pub->path;
        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);
        $materials = Material::where('points','!=','0')->get();
        return View::make('materials.myindex', compact('materials','PATH','customer'));
    }

//
//	/**
//	 * Show the form for creating a new resource.
//	 *
//	 * @return Response
//	 */
//	public function create()
//	{
//		//
//        $type = Input::get('type');
//
//        if($type == 1){
//            $title = '新增单图文消息';
//            return View::make('materials.createone')->with('title',$title);
//        }else{
//            $title = '新增多图文消息';
//            return View::make('materials.createmore')->with('title',$title);
//        }
//	}
//
//
//	/**
//	 * Store a newly created resource in storage.
//	 *
//	 * @return Response
//	 */
//	public function store()
//	{
//		//
//        var_dump(Input::all());
//
////        $filepath = dirname(__FILE__)."\winter.jpg";
////        echo $filepath;
////        exit;
////        $pre = "images/".date("YmdHis",time());
////        $picture = [
////            'image' => $_FILES['picture']['name'],
////        ];
////        $rules = [
////            'image' => array('regex:/^[^&%]*\\.(jpg|gif|jpeg|png|bmp)$/u'),
////        ];
////        $messages = array(
////            'regex' => 'Please check there is no & and % character in the file path and is an image file!!'
////        );
////        $valid = Validator::make($picture, $rules, $messages);
////
////        if ($valid->passes()) {
////            $file = Input::file('picture');
////                $clientName = $file -> getClientOriginalName();
////                $tmpName = $file ->getFileName();//缓存在tmp文件夹中的文件名例如php8933.tmp 这种类型的.
////                $realPath = $file -> getRealPath();    //这个表示的是缓存在tmp文件夹下的文件的绝对路径
////                $entension = $file -> getClientOriginalExtension(); //上传文件的后缀.
////                $mimeTye = $file-> getMimeType();//大家对mimeType应该不陌生了. 我得到的结果是 image/jpeg.
////
////                $newName = md5(date('ymdhis').$clientName).'.jpg';
////                $path = $file->move('/var/www/bosch/public/uploads/materials/images',$newName);
////
////        }else {
////            return Redirect::back()->withErrors($valid)->withInput();
////        }
//
//        $newName = Input::get('picname');
//        $path = '/var/www/bosch/public/uploads/materials/images/'.$newName;
//
//        $tokencache = $this->get_token();
//
//        $data = $this->get_mediaid($tokencache,$path);
////        if($data['errcode'] == '40004'){
////            echo 'error';
////        }else{
//        $ifshow = Input::get('show_cover_pic');
//        if($ifshow != 1){
//            $ifshow = 0;
//        }
//
//        $news[] = array(
//            "thumb_media_id"=>$data['media_id'],
//            "author"=>Input::get('author'),
//            "title"=>Input::get('title'),
//            "content_source_url" =>Input::get('link'),
//            "content" =>Input::get('editorValue'),
//            "digest" =>Input::get('summary'),
//        );
////            var_dump($news);
//
//        $return = $this->upload_news($news,$tokencache);
//
//        var_dump($return);
//
//
//        $material = Material::create(array(
//            'title' => Input::get('title'),
//            'author' => Input::get('author'),
//            'image' => '/uploads/materials/images/'.$newName,
//            'link' => Input::get('link'),
//            'summary' => Input::get('summary'),
//            'content' => Input::get('editorValue'),
//            'show_cover_pic' => $ifshow,
//            'type'=>'1',
//            'theme'=>'1',
//            'theme_name'=>Input::get('type'),
//        ));
//
//
//        $push = array(
//            "mic"=>$material->id,
//            "pic"=>'/uploads/materials/images/'.$newName,
//            "title"=>Input::get('title'),
//            "content_source_url" =>Input::get('link'),
//            "digest" =>Input::get('summary'),
//        );
//
//        Push::create(array(
//            'content' => json_encode($push),
//            'media_id' => $return->media_id,
//            'type' => 1,
//        ));
//
////            var_dump($return);
////        }
////        echo '?';
//	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
        $customer_id = Input::get('customer_id');
        $pub = Pub::find(1);

        $PATH = $pub->path;
        $material = Material::find($id);


        $pub = Pub::find(1);
        require_once app_path().'/lib/wjs/jssdk.php';
        $jssdk = new JSSDK($pub->AppID,$pub->AppSecret);
        $signPackage = $jssdk->GetSignPackage();


        if($customer_id > 0){
            $customer = Customer::find($customer_id);
            $count = Customerpo::where('customer_id',$customer_id)->where('material_id',$id)->count();
            if($count == 0){
                $customerpo = new Customerpo();
                $customerpo->customer_id = $customer_id;
                $customerpo->material_id = $id;
                $customerpo->save();

                $customer->all_points = $customer->all_points+$material->points;
                $customer->save();

                Pointrecord::new_record($material->points,1,1,$id,$customer_id);
            }
        }elseif(Session::has('customer_id'))
        {
            //
            $customer_id = Session::get('customer_id');
            $customer = Customer::find($customer_id);
            $count = Customerpo::where('customer_id',$customer_id)->where('material_id',$id)->count();
            if($count == 0){
                $customerpo = new Customerpo();
                $customerpo->customer_id = $customer_id;
                $customerpo->material_id = $id;
                $customerpo->save();

                $customer->all_points = $customer->all_points+$material->points;
                $customer->save();

                Pointrecord::new_record($material->points,1,1,$id,$customer_id);
            }
        }
        return View::make('materials.show', compact('material','PATH','customer','id','signPackage'));
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
        $push = Push::find($id);
        if($push->type == 1){
            $data = (array)json_decode($push->content);
            $material = Material::find($data['mic']);
            $title = $material->title.' 编辑';
            return View::make('materials.showone', compact('push','data','material','title'));
        }else{

            $jcon = json_decode($push->content,true);
            $ncon = array();
            foreach ($jcon as $k=>$v){
                $material = Material::find($v['mic']);
                $v['con'] = $material->content;
                $ncon[] = $v;
            }
            $ysdata = json_encode($ncon);
            return View::make('materials.showmore', compact('push','ysdata'));
        }

	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update()
	{
		//
        echo Input::get('type');
        if(Input::get('push_type') == 1){

            $newName = Input::get('picname');
            $path = '/var/www/bosch/public'.$newName;

            $tokencache = $this->get_token();

            $data = $this->get_mediaid($tokencache,$path);
//        if($data['errcode'] == '40004'){
//            echo 'error';
//        }else{
            $ifshow = Input::get('show_cover_pic');
            if($ifshow != 1){
                $ifshow = 0;
            }

            $news[] = array(
                "thumb_media_id"=>$data['media_id'],
                "author"=>Input::get('author'),
                "title"=>Input::get('title'),
                "content_source_url" =>Input::get('link'),
                "content" =>Input::get('editorValue'),
                "digest" =>Input::get('summary'),
            );
//            var_dump($news);

            $return = $this->upload_news($news,$tokencache);

            var_dump($return);

            $material = Material::create(array(
                'title' => Input::get('title'),
                'author' => Input::get('author'),
                'image' => $newName,
                'link' => Input::get('link'),
                'summary' => Input::get('summary'),
                'content' => Input::get('editorValue'),
                'show_cover_pic' => $ifshow,
                'type'=>'1',
                'theme'=>'1',
                'theme_name'=>Input::get('type'),
            ));


            $push = array(
                "mic"=>$material->id,
                "pic"=>$newName,
                "title"=>Input::get('title'),
                "content_source_url" =>Input::get('link'),
                "digest" =>Input::get('summary'),
            );

            $pushold = Push::find(Input::get('pid'));
            $pushold->media_id = $return->media_id;
            $pushold->content = json_encode($push);
            $pushold->save();

            return Redirect::action('MaterialsController@index');
        }
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

    public function delete_m(){

        $id = Input::get('id');
        Push::destroy($id);
        echo 'ok';
    }

    public function ajax_json(){
        $pusholdid = Input::get('id');
//        print_r(Input::get('id'));
        $tokencache = $this->get_token();
        $newArray = Input::get('data');
//
//        print_r($newArray);
//
//        $newArray = Array
//        (
//            Array
//            (
//                'tit' => 'dfgsdf',
//            'pic' => '/uploads/materials/images/b6989586ef52665e67eaa59e459b5d00.jpg',
//            'url' => 'asdfasdf',
//            'con' => 'asdfasdf'
//            ),
//
//            Array
//            (
//                'tit' => 'gsdfgsdfgd标题',
//                'pic' => '/uploads/materials/images/69e5956dfba5252ea6f87701fd67b182.jpg',
//                'url' => 'asfdasd',
//                'con' => 'fghsdfgsdfgadsg'
//            )
//
//        );


        foreach($newArray as $key => $val){
            $path = '/var/www/bosch/public'.$val['pic'];
            $val['media'] = $this->get_mediaid($tokencache,$path);
            $news[] = array(
                "thumb_media_id"=>$val['media']['media_id'],
                "author"=>'',
                "title"=>$val['tit'],
                "content_source_url" =>$val['url'],
                "content" =>$val['con'],
                "digest" =>'',
            );



            $material = Material::create(array(
                'title' => $val['tit'],
                'author' => '',
                'image' => $val['pic'],
                'link' => $val['url'],
                'summary' => '',
                'content' => $val['con'],
                'show_cover_pic' => '',
                'type'=>'2',
                'theme'=>'1',
                'theme_name'=>'',
            ));



            $push[] = array(
                "mic"=>$material->id,
                "pic"=>$val['pic'],
                "title"=>$val['tit'],
                "content_source_url" =>$val['url'],
                "digest" =>'',
            );

        }
        $return = $this->upload_news($news,$tokencache);


        if($pusholdid > 0){
            $pushold = Push::find(Input::get('id'));
            $pushold->media_id = $return->media_id;
            $pushold->content = json_encode($push);
            $pushold->save();
        }else{
            Push::create(array(
                'content' => json_encode($push),
                'media_id' => $return->media_id,
                'type' => 2,
            ));
        }




        echo 'ok';

    }

    public function ajax_upload_pic()
    {

//        $pre = "images/".date("YmdHis",time());
//        $picture = [
//            'image' => $_FILES['fileToUpload']['name'],
//        ];
//        $rules = [
//            'image' => array('regex:/^[^&%]*\\.(jpg|gif|jpeg|png|bmp)$/u'),
//        ];
//        $messages = array(
//            'regex' => 'Please check there is no & and % character in the file path and is an image file!!'
//        );
//        $valid = Validator::make($picture, $rules, $messages);

//        if ($valid->passes()) {
            $file = Input::file('fileToUpload');
            $clientName = $file -> getClientOriginalName();
            $tmpName = $file ->getFileName();//缓存在tmp文件夹中的文件名例如php8933.tmp 这种类型的.
            $realPath = $file -> getRealPath();    //这个表示的是缓存在tmp文件夹下的文件的绝对路径
            $entension = $file -> getClientOriginalExtension(); //上传文件的后缀.
            $mimeTye = $file-> getMimeType();//大家对mimeType应该不陌生了. 我得到的结果是 image/jpeg.

            $newName = md5(date('ymdhis').$clientName).'.jpg';
            $path = $file->move('/var/www/bosch/public/uploads/materials/images',$newName);
            $msg['error'] = 'ok';
            $msg['pic_name'] = $newName;
            echo json_encode($msg);
//        }else {
//            return Redirect::back()->withErrors($valid)->withInput();
//        }
    }


    public function upload_news($news,$token){
//        var_dump($news);
        $data2 = array('articles'=>$news);
        foreach($news as $key => $val){
            foreach($val as $k => $v){
                $news[$key][$k] = urlencode($v);
            }
        }

        $data = array('articles'=>$news);
//        var_dump($data);
        $news_data = urldecode(json_encode($data));
//        echo $news_data;

//        echo '<br>------------------------------------------------------------------------------------<br>';

        $news_data2 = json_encode($data2);
//        echo $news_data2;


//        echo '<br>------------------------------------------------------------------------------------<br>';

        $news_data3 = preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $news_data2);


        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='.$token;
        $res = $this->https_request($url,$news_data3 );
        return json_decode($res);
    }

    public function get_mediaid($tokencache,$path){
////        echo $tokencache;
////        $http = 'https://api.weixin.qq.com/cgi-bin/groups/get?access_token='.$tokencache;
////        $json = $this->http_request_json($http);//这个地方不能用file_get_contents
////        $data=json_decode($json,true);
////        var_dump($data);
        $type = "image";
        $filedata = array("file1"  => "@".$path);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$tokencache&type=$type";
        $result = $this->https_request($url, $filedata);
//        $data['errcode'] = '';
        $data=json_decode($result,true);
        return $data;
    }

    public function get_token(){


        $config = Manger::firstOrFail();
        $minutes = '120';
        $a = App::make('dimensions'); // 用法
        $tokencache = $a->get_access_token($config->appid,$config->appsecret);
        Cache::put('token', $tokencache, $minutes);

        return $tokencache;
    }

    public function http_request_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**************************************************************
     *
     *  将数组转换为JSON字符串（兼容中文）
     *  @param  array   $array      要转换的数组
     *  @return string      转换得到的json字符串
     *  @access public
     *
     *************************************************************/
    function JSON($array) {
        array_walk_recursive($array['articles'], 'urlencode');
        $json = json_encode($array);
        return urldecode($json);
    }
}
